package com.niiwoo.civet.user.mq;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.user.constants.UserRabbitConstant;
import com.niiwoo.civet.user.dto.request.DataBackFlowRetryMQDTO;
import com.niiwoo.civet.user.service.local.dataflow.DataBackFlowRetryService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: wuke
 * @Description:
 * @Date: Created in 14:35 2018/1/11
 */
@Slf4j
@Component
public class DataBackFlowRetryListener {
    @Autowired
    private DataBackFlowRetryService dataBackFlowRetryService;

    @RabbitListener(queues = UserRabbitConstant.Queue.DATA_BACKFLOW_RETRY)
    public void onReceiveDataBackFlowRetry(DataBackFlowRetryMQDTO dataBackFlowRetryMQDTO, Message message, Channel channel) throws IOException {
        long time = System.currentTimeMillis();
        log.info("onReceiveDataBackFlowRetry.time={},dataBackFlowRetryMQDTO={}", time,JSON.toJSONString(dataBackFlowRetryMQDTO));
        try {
            dataBackFlowRetryService.dataBackFlowPushToTianCheng(dataBackFlowRetryMQDTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.error("onReceiveDataBackFlowRetry.time={} error", time,e);
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException e1) {
                log.error("onReceiveDataBackFlowRetry.time={} basicNack error", time,e);
            }
        }
        log.info("onReceiveDataBackFlowRetry.time={} end", time);
    }
}
